package com.nervenets.template.service.impl;

import com.nervenets.general.redis.RedisSyncLocker;
import com.nervenets.general.service.impl.BaseServiceImpl;
import com.nervenets.general.utils.JodaUtils;
import com.nervenets.template.hibernate.dao.DataOfGoldDao;
import com.nervenets.template.hibernate.domain.data.DataOfGold;
import com.nervenets.template.service.DataOfGoldService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class DataOfGoldServiceImpl extends BaseServiceImpl<DataOfGold, DataOfGoldDao> implements DataOfGoldService {
    @Resource
    private RedisSyncLocker<Void> redisSyncLocker;

    @Override
    public DataOfGold checkAndGenerateData(long timestamp) {
        DataOfGold dataOfGold = dao.findByCreateTime(timestamp);
        if (null == dataOfGold) {
            dataOfGold = new DataOfGold();
            dataOfGold.setCreateTime(timestamp);
            save(dataOfGold);
        }
        return dataOfGold;
    }

    @Override
    public void updateData(long total, long platformSpend, long totalExchange) throws Exception {
        final long startOfToday = JodaUtils.getStartOfToday();
        redisSyncLocker.keyLock("DataOfGold" + startOfToday, () -> {
            DataOfGold dataOfGold = checkAndGenerateData(startOfToday);
            if (total != 0) dataOfGold.setTotal(total);
            if (platformSpend != 0) dataOfGold.setPlatformSpend(platformSpend);
            if (totalExchange != 0) dataOfGold.setTotalExchange(totalExchange);
            save(dataOfGold);
            return null;
        });
    }
}
